<?php


namespace app\controller;

use app\BaseController;
use app\model\AdvertModel;
use think\Request;
use think\Response;
use think\facade\Db;
use app\model\BannerModel;
use app\validate\BannerValidate;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Writer\Csv;
use app\common\Snowflake;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\facade\Request as FileRequest;

class Banner extends BaseController {

    // 统一响应格式
    private function jsonResponse(int $code, string $msg, $data = []): Response
    {
        return json(compact('code', 'msg', 'data'));
    }

    /**
     * 列表+搜索
     */
    public function list(Request $request)
    {
        $params = $request->only(['banner_id', 'title', 'type', 'is_show']);
        $query = BannerModel::field('id,banner_id,title,file_url,type,jump_type,jump_url,is_show,sort,update_time');

        // 搜索条件
        if (!empty($params['banner_id'])) $query->where('banner_id', $params['banner_id']);
        if (!empty($params['title'])) $query->whereLike('title', "%{$params['title']}%");
        if (isset($params['type'])) $query->where('type', $params['type']);
        if (isset($params['is_show'])) $query->where('is_show', $params['is_show']);

        $data = $query->order('sort asc, id desc')->paginate();
        return $this->jsonResponse(0, 'success', $data);
    }

    /**
     * 新增
     */
    public function create()
    {
        $data = $this->request->post();
        validate(BannerValidate::class)->check($data);

        $snowflake = new Snowflake(1, 1);
        $data['banner_id'] = $snowflake->nextId();
        $banner = BannerModel::create($data);

        return $this->jsonResponse(0, '添加成功', $banner);
    }

    /**
     * 编辑
     */
    public function update($id)
    {
        $data = $this->request->post();
        validate(BannerValidate::class)->check($data);
        $result = Db::name('banner')->where('id', $id)->update($data);

        if ($result) {
            return json(['code' => 0, 'msg' => '更新成功']);
        } else {
            return json(['code' => 1, 'msg' => '更新失败']);
        }
    }

    /**
     * 删除
     */
    public function delete($id)
    {
        $banner = BannerModel::findOrFail($id);
        $banner->delete();
        return $this->jsonResponse(0, '删除成功');
    }

    /**
     * 导入
     */
    public function import(Request $request)
    {
        $file = FileRequest::file('file');
        if (!$file) {
            return json(['code' => 1, 'msg' => '请上传文件', 'data' => []]);
        }

        try {
            $spreadsheet = IOFactory::load($file->getRealPath());
            $sheet = $spreadsheet->getActiveSheet();
            $highestRow = $sheet->getHighestRow();

            $data = [];
            $snowflake = new Snowflake(1, 1);

            for ($row = 2; $row <= $highestRow; $row++) {
                $fileUrl = $sheet->getCell('A' . $row)->getValue();
                $jumpType = $sheet->getCell('B' . $row)->getValue();
                $jumpUrl = $sheet->getCell('C' . $row)->getValue();
                $sort = $sheet->getCell('D' . $row)->getValue();
                $isShow = $sheet->getCell('E' . $row)->getValue();

                if (!$fileUrl || !in_array($jumpType, [0, 1, 2])) {
                    continue; // 跳过必填字段缺失或跳转类型无效的数据
                }

                $data[] = [
                    'ad_id' => $snowflake->nextId(),
                    'file_url' => $fileUrl,
                    'jump_type' => $jumpType,
                    'jump_url' => $jumpUrl,
                    'sort' => $sort,
                    'is_show' => $isShow!== null? $isShow : 1,
                    'create_time' => date('Y-m-d H:i:s'),
                    'update_time' => date('Y-m-d H:i:s')
                ];
            }

            if (!empty($data)) {
                AdvertModel::insertAll($data);
            }

            return json(['code' => 0, 'msg' => '导入成功', 'data' => []]);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '导入失败：' . $e->getMessage(), 'data' => []]);
        }
    }


    /**
     * 导出
     */
    public function export(Request $request)
    {
        // 1. 获取查询参数（与列表接口保持一致）
        $params = $request->only(['banner_id', 'title', 'type', 'is_show']);

        // 2. 构建基础查询 在field()中明确包含id字段
        $query = BannerModel::field('id,banner_id,title,type,file_url,jump_type,jump_url,sort,is_show,update_time')
            ->order('sort asc, id desc'); // ✅ 现在id字段已存在

        // 3. 应用过滤条件（与列表接口相同逻辑）
        if (!empty($params['banner_id'])) {
            $query->where('banner_id', $params['banner_id']);
        }
        if (!empty($params['title'])) {
            $query->whereLike('title', "%{$params['title']}%");
        }
        if (isset($params['type'])) {
            $query->where('type', $params['type']);
        }
        if (isset($params['is_show'])) {
            $query->where('is_show', $params['is_show']);
        }

        // 4. 创建Spreadsheet对象
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        // 5. 设置表头（根据实际字段）
        $headers = [
            '轮播图ID', '标题', '类型', '文件URL',
            '跳转类型', '跳转地址', '排序', '是否展示', '最后更新时间'
        ];
        $sheet->fromArray($headers, null, 'A1');

        // 6. 分批获取数据（防止内存溢出）
        $query->chunk(1000, function($items) use ($sheet) {
            foreach ($items as $item) {
                // 转换枚举值为可读文本
                $rowData = [
                    $item->banner_id,
                    $item->title,
                    $item->type == 1 ? '图片' : '视频',
                    $item->file_url,
                    match($item->jump_type) {
                        0 => '无跳转',
                        1 => '端内跳转',
                        2 => '端外跳转',
                        default => '未知'
                    },
                    $item->jump_url,
                    $item->sort,
                    $item->is_show ? '展示' : '隐藏',
                    $item->update_time
                ];

                // 追加数据行
                $sheet->fromArray($rowData, null, 'A' . ($sheet->getHighestRow() + 1));
            }
        });

        // 7. 根据请求类型生成不同格式
        $format = $request->param('format', 'xlsx');

        // 8. 设置输出参数
        $filename = 'banners_' . date('YmdHis');
        header('Content-Type: application/octet-stream');

        // 9. 生成文件
        if ($format === 'csv') {
            // CSV配置
            $writer = new Csv($spreadsheet);
            $writer->setDelimiter(',');
            $writer->setEnclosure('"');
            $writer->setLineEnding("\r\n");
            $filename .= '.csv';
            header('Content-Type: text/csv');
        } else {
            // XLSX配置（默认）
            $writer = new Xlsx($spreadsheet);
            $writer->setPreCalculateFormulas(false); // 提升性能
            $filename .= '.xlsx';
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        }

        // 10. 输出文件
        header('Content-Disposition: attachment;filename="' . $filename . '"');
        header('Cache-Control: max-age=0');
        $writer->save('php://output');
        exit;


    }
}